package com.teacold.customdemo.chapter_ten;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.GradientDrawable;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.teacold.customdemo.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;

import androidx.appcompat.app.AppCompatActivity;

public class TenActivity extends AppCompatActivity implements View.OnClickListener {
    private Button ten_button;
    private TextView ten_text;
    private ImageView ten_image, ten_image2;
    private String path = "http://img.multshows.com/pc/image/20180712/ee155f4ee30444df9ab435533ff377af.png";
    private int ang = 4;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ten);
        initView();
    }

    private void initView() {
        ten_button = findViewById(R.id.ten_button);
        ten_text = findViewById(R.id.ten_text);
        ten_image = findViewById(R.id.ten_image);
        ten_image2 = findViewById(R.id.ten_image2);
        ten_button.setOnClickListener(this);
//        downloadImage();
//        compressImage();
//        imageCompress(ang);
        Paint paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setAntiAlias(true);
        paint.setTextSize(10);
        Bitmap bitmap = Bitmap.createBitmap(200, 100, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        canvas.drawText("这是一只狗", 20, 30, paint);
        Bitmap src=BitmapFactory.decodeResource(getResources(),R.drawable.dog);
        ten_image2.setImageBitmap(createWaterBitmap(src,bitmap));

//        saveImage();
    }

    /**
     * 生成水印
     */
    private Bitmap createWaterBitmap(Bitmap src, Bitmap watermark) {
        if (src == null) {
            return null;
        }
        int w = src.getWidth();
        int h = src.getHeight();
        int ww = watermark.getWidth();
        int wh = watermark.getHeight();
        //创建空白图像
        //创建一个新的src长度、宽度一样的bitmap
        Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newb);
        //画原图
        canvas.drawBitmap(src, 0, 0, null);
        canvas.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);
        return newb;
    }


    /**
     * 保存图片
     */
    private void saveImage() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dog);
        File fileDir = Environment.getExternalStorageDirectory();
        String path = fileDir.getAbsolutePath() + "lavor.webp";
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.WEBP, 1, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    /**
     * 压缩图片
     * Bitmap.CompressFormat.JPEG 有损压缩 不带有alpha透明度
     * Bitmap.CompressFormat.PNG
     */
    private void imageCompress(int mage) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.grassland);
        ten_image.setImageBitmap(bitmap);
        //压缩图像后显示
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.WEBP, ang, bos);
        byte[] bytes = bos.toByteArray();
        Bitmap bitmap1 = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        ten_image2.setImageBitmap(bitmap1);
    }


    /**
     * setPixel()
     * getPixel()  针对某个位置的像素进行设置和获取
     */
    private void setPixelBimap() {
        Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.grassland);
        ten_image.setImageBitmap(srcBitmap);
        Bitmap desBmp = srcBitmap.copy(Bitmap.Config.ARGB_8888, true);
        for (int h = 0; h < srcBitmap.getHeight(); h++) {
            for (int w = 0; w < srcBitmap.getWidth(); w++) {
                int originColor = srcBitmap.getPixel(w, h);
                int red = Color.red(originColor);
                int alpha = Color.alpha(originColor);
                int green = Color.green(originColor);
                int blue = Color.blue(originColor);
                if (green < 200) {
                    green += 30;
                }
                desBmp.setPixel(w, h, Color.argb(alpha, red, green, blue));
            }
        }
        ten_image2.setImageBitmap(desBmp);
    }


    private void setImageView() {
        Bitmap srcBimap = BitmapFactory.decodeResource(getResources(), R.drawable.dog);
        Paint alphaPaint = new Paint();
        BlurMaskFilter blurMaskFilter = new BlurMaskFilter(6, BlurMaskFilter.Blur.NORMAL);
        alphaPaint.setMaskFilter(blurMaskFilter);
        int[] offsetXY = new int[2];
        Bitmap alphaBmp = srcBimap.extractAlpha(alphaPaint, offsetXY);
        Bitmap bitmap = Bitmap.createBitmap(alphaBmp.getWidth(), alphaBmp.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setColor(Color.CYAN);
        canvas.drawBitmap(alphaBmp, 0, 0, paint);
        ten_image.setImageBitmap(alphaBmp);
        srcBimap.recycle();
    }


    private void compressImage() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.one);
        Log.e("图片的bitmap是否为null", (bitmap == null) + " 宽" + bitmap.getWidth() + "   高" + bitmap.getHeight());


    }

    private void downloadImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] data = getImage(path);
                    int length = data.length;
                    final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, length);
                    ten_image.post(new Runnable() {
                        @Override
                        public void run() {
                            ten_image.setImageBitmap(bitmap);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private byte[] getImage(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(6 * 1000);
            InputStream in = null;
            Log.e("ssssss下载图片", "" + httpURLConnection.getResponseCode());
            if (httpURLConnection.getResponseCode() == 200) {
                in = httpURLConnection.getInputStream();
                byte[] result = readStream(in);
                in.close();
                return result;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] readStream(InputStream in) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = in.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        in.close();
        return outputStream.toByteArray();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ten_button:
                GradientDrawable gradientDrawable = (GradientDrawable) ten_text.getBackground();
                gradientDrawable.setCornerRadius(50);
                break;
        }
    }


}
